package com.ysh.smartplatform.event.listener;

import com.ysh.smartplatform.event.DeviceCommandEvent;
import com.ysh.smartplatform.pojo.Humiture;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 袁胜虎 on 2022/9/14 21:05
 */
@Component
public class HumitureListener {
    private ApplicationContext applicationContext;

    @Autowired
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
    private final List<Humiture>  humitures = new CopyOnWriteArrayList<>();

    @EventListener
    @Async
    public void onHumiture(Humiture humiture){
        //当我们收到温湿度的数据的时候
        //计算平均值,我们直接保存到一个集合中,然后每一分钟拿出里面的数据计算一次平均值,然后将数据放入到数据库中
        humitures.add(humiture);
    }
    /**
     * 1分钟执行一次计算
     */
    @Scheduled(fixedRate = 60000)
    public void checkHumiture(){
        if(humitures.size()==0){
            return;
        }
        ArrayList<Humiture> subList = new ArrayList<>();
        subList.addAll(humitures);
        humitures.clear();
        //计算温度的平均值
        double tempAvg = subList.stream().mapToDouble(Humiture::getTemperature).average().getAsDouble();
        if (tempAvg>0){
            if (tempAvg>35){
                System.err.println("当前温度大于设定的阈值,打开空调");
                applicationContext.publishEvent(new DeviceCommandEvent("124233","0"));
            }else if (tempAvg<32){
                System.err.println("当前温度小于设定的阈值,关闭空调");
                applicationContext.publishEvent(new DeviceCommandEvent("124233","1"));
            }
        }
    }
}
